package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @Author: cl
 * @Date: 2022/5/11 - 05 - 11
 * @Description:
 */

/**
 * 访客数据表服务
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客数据
     *
     * @param visitors
     * @return
     */
    @Override
    public void save(Visitors visitors) {

        //1、查询是否有访客数据
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId()));
        if (!mongoTemplate.exists(query, Visitors.class)) {
            //2、如果没有就创建访客数据
            mongoTemplate.save(visitors);
        } else {
            //3、如果有就更新访客数据(更新访客时间)
            Update update = Update.update("date", visitors.getDate());
            mongoTemplate.updateFirst(query, update, Visitors.class);
        }
    }

    /**
     * 获取最新访客
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public List<Visitors> getNewUser(Long userId, Long time) {

        //1、创建条件
        Criteria criteria = Criteria.where("userId").is(userId);
        if (time != null) {
            criteria.and("date").gt(time);
        }
        //2、查询访客
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        //3、返回访客
        return mongoTemplate.find(query, Visitors.class);
    }

    /**
     * 获取所有访客
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Visitors> getAll(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query, Visitors.class);
    }
}
